package book.interceptor;

import book.contant.SessionContent;
import book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 定义拦截器
 * 实现HandlerInterceptor接口,重写preHandle方法,进行配置
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在目标方法执行前执行
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return  true:不进行拦截,继续进行后面的操作
     *          false: 进行拦截,停止执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       log.info("目标方法执行前执行...");
//       从请求中获取Session,调用传参方法,传入false:当未获取到Session时,返回null,
//           调用不传参方法和调用传参,传入true方法 功能相同:当未获取到Session时,创建Session
        HttpSession session=request.getSession();
        UserInfo userinfo = (UserInfo)session.getAttribute(SessionContent.USER_SESSION_KEY);
        if (userinfo ==null ){
    //            当未获取到Session时,或用户为登录时,设置状态码为401 Unauthorized: 未经授权,
    //            返回false,进行拦截
                response.setStatus(401);
                return false;
            }
        return true;

    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
////        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//        log.info("目标方法执行后执行...");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
////        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        log.info("视图渲染完成后执行,最后执行...");
//    }

}
